package com.chuanyang.driverh.mainstart.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.PointF;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chuanyang.driverh.BaseApplication;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseFragment;
import com.chuanyang.driverh.mainhome.SystemMessageActivity;
import com.chuanyang.driverh.mainstart.MainActivityDriver;
import com.chuanyang.driverh.mainstart.MainActivityLeader;
import com.chuanyang.driverh.responseresult.DriverInfoData;
import com.chuanyang.driverh.utils.JsonUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.eventbus.MessageData;
import com.chuanyang.driverh.utils.eventbus.RefleshFragEvent;
import com.chuanyang.driverh.utils.eventbus.RefleshMessageEvent;
import com.chuanyang.driverh.utils.widget.GooViewListener;
import com.chuanyang.driverh.utils.widget.SwipeLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;


public class RealtimeFragment extends BaseFragment {

    private Context mContext;
    private HashMap params;
    private ArrayList<MessageData> trafficlist;
    private ArrayList<MessageData> instantlist;
    private ArrayList<MessageData> systemlist;
    private TextView tv_system_count;
    private TextView tv_traffic_message;
    private TextView tv_traffic_time;
    private TextView tv_traffic_count;
    private TextView tv_realtime_meassage;
    private TextView tv_instant_time;
    private TextView tv_instant_count;
    private TextView tv_system_message;
    private TextView tv_system_time;
    private TextView tv_instant_meassage;
    private TextView tv_homecount;
    private SwipeLayout sl_2;
    HashSet<SwipeLayout> mUnClosedLayouts = new HashSet<SwipeLayout>();
    HashSet<TextView> mRemoved = new HashSet<TextView>();


    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_realtime;
    }

    @Override
    public void initView(View view) {

        findView();
    }

    private void findView() {
        BaseApplication.getInstance().setDriverInfo();
        DriverInfoData driverInfoData= BaseApplication.getInstance().getDriverInfo();
       /* if (driverInfoData!=null &&driverInfoData.getFleet()!=null && driverInfoData.getFleet().getFleetLeader().equals(driverInfoData.getDriverId())){
            MainActivityDriver mainActivityDriver = (MainActivityDriver) getActivity();
            tv_homecount = mainActivityDriver.getHasMessageCount();
        }else{
            MainActivityLeader mainActivityLeader = (MainActivityLeader) getActivity();
            tv_homecount = mainActivityLeader.getHasMessageCount();
        }*/


        if (getActivity() instanceof MainActivityDriver ){
            tv_homecount = ((MainActivityDriver)getActivity()).getHasMessageCount();
        }else if(getActivity() instanceof MainActivityLeader ){
            tv_homecount = ((MainActivityLeader)getActivity()).getHasMessageCount();
        }


        LinearLayout layout_group_chat = (LinearLayout) rootView.findViewById(R.id.layout_group_chat);
        LinearLayout layout_contact = (LinearLayout) rootView.findViewById(R.id.layout_contact);
        LinearLayout layout_friend_new = (LinearLayout) rootView.findViewById(R.id.layout_friend_new);
        LinearLayout btn_search = (LinearLayout) rootView.findViewById(R.id.btn_search);
        RelativeLayout layout_traffic = (RelativeLayout) rootView.findViewById(R.id.layout_traffic);
        RelativeLayout real_time = (RelativeLayout) rootView.findViewById(R.id.real_time);
        LinearLayout layout_system = (LinearLayout) rootView.findViewById(R.id.layout_system);
        sl_2 = (SwipeLayout) rootView.findViewById(R.id.s2);
        tv_traffic_message = (TextView) rootView.findViewById(R.id.tv_traffic_message);
        tv_traffic_time = (TextView) rootView.findViewById(R.id.tv_traffic_time);
        tv_traffic_count = (TextView) rootView.findViewById(R.id.tv_traffic_count);
        tv_instant_meassage = (TextView) rootView.findViewById(R.id.tv_instant_meassage);
        tv_instant_time = (TextView) rootView.findViewById(R.id.tv_instant_time);
        tv_instant_count = (TextView) rootView.findViewById(R.id.tv_instant_count);
        tv_system_message = (TextView) rootView.findViewById(R.id.tv_system_message);
        tv_system_time = (TextView) rootView.findViewById(R.id.tv_system_time);
        tv_system_count = (TextView) rootView.findViewById(R.id.tv_system_count);
        layout_traffic.setOnClickListener(this);
        real_time.setOnClickListener(this);
        layout_system.setOnClickListener(this);
        sl_2.setOnSwipeListener(new SwipeLayout.OnSwipeListener() {
            @Override
            public void onOpen(SwipeLayout layout) {
                mUnClosedLayouts.add(layout);

            }

            @Override
            public void onClose(SwipeLayout layout) {
                mUnClosedLayouts.remove(layout);

            }

            @Override
            public void onStartOpen(SwipeLayout layout) {

            }

            @Override
            public void onStartClose(SwipeLayout layout) {
                closeAllLayout();
                mUnClosedLayouts.add(layout);
            }
        });
    }

    @Override
    protected void onForceRefresh() {
        onShowContent();
    }

    @Override
    public void initData() {
        mContext = getActivity().getApplicationContext();
        // reconnect();
        setMessageCount();
    }

    @Override
    protected void initListener() {

    }

//    private void reconnect() {
//        if (mContext.getApplicationInfo().packageName.equals(ProcressManager.getCurProcessName(mContext))) {
//            Log.d("LoginActivity", "process not error");
//            RongIMClient.connect(PreferencesUtil.getStringPreferences(mContext, "token"), new RongIMClient.ConnectCallback() {
//                @Override
//                public void onTokenIncorrect() {
//                    Log.d("LoginActivity", "--onTokenIncorrect");
//                }
//
//                @Override
//                public void onSuccess(String userid) {
//                    Log.d("LoginActivity", "--onSuccess :" + userid);
//                    initConversationListFragment();
//                    //startActivity(new Intent(LoginActivity.this, MainActivity.class));
//                    //    finish();
//                }
//
//                @Override
//                public void onError(RongIMClient.ErrorCode errorCode) {
//
//                    Log.d("LoginActivity", "--onError" + errorCode);
//                }
//            });
//        } else {
//            Log.d("LoginActivity", "process error");
//        }
//    }
//
//    private void initConversationListFragment() {
//        ConversationListFragment fragment = new ConversationListFragment();
//        fragment.setAdapter(new MyConversationListAdapter(mContext));
//        Uri uri = Uri.parse("rong://" + getActivity().getApplicationInfo().packageName).buildUpon()
//                .appendPath("conversationlist")
//                .appendQueryParameter(io.rong.imlib.model.Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话是否聚合显示
//                .appendQueryParameter(io.rong.imlib.model.Conversation.ConversationType.GROUP.getName(), "false")
//                .build();
//        fragment.setUri(uri);
//        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
//        //xxx 为你要加载的 id
//        transaction.add(R.id.conversation_list_content, fragment);
//        transaction.commitAllowingStateLoss();
//
//    }

//
//    @Override
//    public void onDestroyView() {
//        super.onDestroyView();
//        ButterKnife.unbind(this);
//    }

    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.layout_group_chat:
//               // startActivity(GroupChatActivity.class);
//
//                break;
//            case R.id.layout_contact:
//               //startActivity(ContacterActivity.class);
//
//                break;
//            case R.id.layout_friend_new:
//            //    startActivity(NewFriendActivity.class);
//
//                break;
//            case R.id.btn_search:
//               // startActivity(SearchActivity.class);
//                break;
            case R.id.layout_traffic:
                //startActivity(TrafficActivity.class);
                break;
            case R.id.real_time:
                String instantStr = JsonUtil.parseBeanToJson(instantlist);
                Intent intent2 = new Intent(getActivity(), SystemMessageActivity.class);
                intent2.putExtra("type", 3);
//                intent2.putExtra("data", instantStr);
                startActivity(intent2);
                break;
            case R.id.layout_system:
                Intent intent1 = new Intent(getActivity(), SystemMessageActivity.class);
                intent1.putExtra("type", 1);
//                intent1.putExtra("data", systemStr);
                startActivity(intent1);

                break;
//            case R.id.conversation_list_content:
//                break;
        }
    }

    public void onEventMainThread(RefleshFragEvent event) {

        if (event.getIndex() == 2) {
            onShowContent();
            setMessageCount();
        }
    }
    private void setMessageCount() {

       /* if (SharedPrefUtil.getPreferences( "messagecount"+ SharedPrefUtil.getUserId(), 0) == null) {
            tv_system_count.setVisibility(View.GONE);
            tv_homecount.setVisibility(View.GONE);
            tv_system_message.setText("无消息");
        } else{

            if (SharedPrefUtil.getPreferences( "messagecount"+SharedPrefUtil.getUserId(), 0) > 99) {
                setUnreadCount(tv_system_count, "99+");
                tv_homecount.setText("99+");

            } else {
                setUnreadCount(tv_system_count, SharedPrefUtil.getPreferences( "messagecount"+SharedPrefUtil.getUserId(), 0) + "");
                tv_homecount.setText(SharedPrefUtil.getPreferences( "messagecount"+SharedPrefUtil.getUserId(), 0) + "");
            }
            if (SharedPrefUtil.getPreferences( "messagecontent"+ SharedPrefUtil.getUserId(), 0) != null)
            tv_system_message.setText(SharedPrefUtil.getPreferences("messagecontent"+SharedPrefUtil.getUserId(),0));
            tv_system_time.setText(DateUtil.calculateTimeBySec(getActivity()));
            tv_system_count.setVisibility(View.VISIBLE);
            tv_homecount.setVisibility(View.VISIBLE);

        }*/
        //tv_system_time.setText(PreferencesUtil.getStringPreferences(getActivity(), "time"+PrefUtils.getInstance(getActivity()).getUserId()));
    }
    public void onEventMainThread(RefleshMessageEvent event) {
        if (event.isReflesh()) {
            setMessageCount();
        }
    }

    //设置粘性控件
    private void setUnreadCount(final TextView tv, String content) {
        tv.setText(content);
        tv.setTag(2);
        GooViewListener mGooListener = new GooViewListener(getActivity(), tv) {
            @Override
            public void onDisappear(PointF mDragCenter) {
                super.onDisappear(mDragCenter);
                tv.setVisibility(View.GONE);
                SharedPrefUtil.setPreferences( "messagecount"+SharedPrefUtil.getUserId(), 0);
                tv_homecount.setVisibility(View.GONE);

            }

            @Override
            public void onReset(boolean isOutOfRange) {
                super.onReset(isOutOfRange);
                tv.setVisibility(View.VISIBLE);


            }
        };
        tv.setOnTouchListener(mGooListener);

    }
    public void closeAllLayout() {
        if(mUnClosedLayouts.size() == 0)
            return;

        for (SwipeLayout l : mUnClosedLayouts) {
            l.close();
        }
        mUnClosedLayouts.clear();
    }

}
